package com.tich.program.listener;

import cn.hutool.core.bean.BeanUtil;
import com.tich.constant.RabbitMqConstant;
import com.tich.program.domain.dto.ProgramMQDeleteDTO;
import com.tich.program.domain.entity.*;
import com.tich.program.mapper.ProgramDeletedMapper;
import com.tich.program.mapper.ProgramShowtimeDeletedMapper;
import com.tich.program.mapper.ProgramTicketDeletedMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Component
public class ProgramListener {

    @Autowired
    private ProgramDeletedMapper programDeletedMapper;
    @Autowired
    private ProgramShowtimeDeletedMapper programShowtimeDeletedMapper;
    @Autowired
    private ProgramTicketDeletedMapper programTicketDeletedMapper;

    @Transactional
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RabbitMqConstant.PROGRAM_DELETE_QUEUE),
            exchange = @Exchange(name = RabbitMqConstant.PROGRAM_DIRECT, type = ExchangeTypes.DIRECT),
            key = {RabbitMqConstant.PROGRAM_DELETE_KEY}
    ))
    public void listenProgramDelete(ProgramMQDeleteDTO programMQDeleteDTO){
        log.info("将已删除的节目以及相关信息添加到删除表中：{}", programMQDeleteDTO);
        //1.添加节目
        ProgramDeleted programDeleted = BeanUtil.copyProperties(programMQDeleteDTO.getProgram(), ProgramDeleted.class);
        programDeletedMapper.insert(programDeleted);
        //2.添加节目详细时间
        ProgramShowtimeDeleted programShowtimeDeleted = BeanUtil.copyProperties(programMQDeleteDTO.getProgramShowtime(), ProgramShowtimeDeleted.class);
        programShowtimeDeletedMapper.insert(programShowtimeDeleted);
        //3.添加节目门票
        List<ProgramTicketDeleted> programTicketDeleteds = BeanUtil.copyToList(programMQDeleteDTO.getProgramTickets(), ProgramTicketDeleted.class);
        programTicketDeletedMapper.insert(programTicketDeleteds);
    }

}
